package nio;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: 康大
 * \* Date: 2019/4/29
 * \* Time: 15:14
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \    阻塞式
 */
public class BlockingNIOTest {
    //客户端
    @Test
    public void client() {
        try(SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8989));
            FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);) {
            ByteBuffer buffer = ByteBuffer.allocate(1027);
            while (inChannel.read(buffer) != -1) {
                buffer.flip();
                inChannel.write(buffer);
                buffer.clear();
            }
            socketChannel.shutdownOutput();
            // 接收服务端反馈
            int len = 0;
            while ((len = socketChannel.read(buffer)) != -1) {
                buffer.flip();
                System.out.println(new String(buffer.array(), 0, len));
                buffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 服务端
    @Test
    public void server() {
        try(ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            FileChannel outChannel = FileChannel.open(Paths.get("2.jpg"),StandardOpenOption.WRITE, StandardOpenOption.CREATE);
            SocketChannel socketChannel = serverSocketChannel.accept();) {
            serverSocketChannel.bind(new InetSocketAddress(8989));
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            while (socketChannel.read(byteBuffer) != -1) {
                byteBuffer.flip();
                outChannel.write(byteBuffer);
                byteBuffer.clear();
            }
            // 发送反馈给客户端
            byteBuffer.put("服务端接收数据成功".getBytes());
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
            socketChannel.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
